var mysql=require('mysql');
var express=require('express');
var app=express();
var fs=require('fs');
var bq=require('body-parser');

var config={
	host 	:'localhost',
	user 	:'root',
	password:'123456',
	database:'test',
	multipleStatements:true,
	//支持多条sql语句
	
}

app.use(bq.json());
app.use(bq.urlencoded({ extended:false}));
//body-parser配置 支持解析post接口数据

var initUser='SELECT * FROM user'
//获取所有用户数据，用作更改表后刷新初始数据

function Msg(success,body){
	//回调参数
	this.success=success;
	this.body=body;
	
}

function querySQL(sql,fn){
	//封装调用sql语句方法
	var connection=mysql.createConnection(config);
	connection.query(sql,function(err,data){
		let msg = err ? new Msg(false,err):new Msg(true,data);
		fn(msg);
		
	});
	connection.end();
}

//二次封装
function returmJsonRes(sql,res){
	querySQL(sql,function(msg){
		res.json(msg);
		res.end();
	})
}

app.get('/getUser',function(req,res){
	// querySQL(initUser,function(msg){
	// 	res.json(msg);
	// 	res.end();
	returmJsonRes(initUser,res);
	
})
//GET 地址栏 query
app.get('/find',function(req,res){
	let u=req.query;
	var sql=`SELECT * FROM user WHERE username='${u.username}';`
	returmJsonRes(sql+initUser,res);

})
//注册
app.post('/register',function(req,res){
	let u=req.body;
	var sql=`insert into user(username,password,sex) 
	values('${u.username}','${u.password}','${u.sex}');`
	
	returmJsonRes(sql+initUser,res);
	
})



app.listen(8000,function(){
	console.log('服务2已经开启，冲 冲 冲！')
	
	
})
	

